package com.windrift.springhibernate.controller;

import com.windrift.springhibernate.model.Cost;
import com.windrift.springhibernate.model.CostType;
import com.windrift.springhibernate.service.CostService;
import com.windrift.springhibernate.service.CostTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author xuweigui
 */
@SuppressWarnings("serial")
@Controller
@RequestMapping(value = "/cost")
public class CostController {
    @Autowired
    private CostService costService;
    @Autowired
    private CostTypeService costTypeService;


    @RequestMapping(value = "/remove/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public void delete(@PathVariable("id") Integer id) {
        costService.remove(id);
    }

    @RequestMapping()
    public String execute(Model model) {
        List<Cost> costs = costService.findAll();
        model.addAttribute("costs", costs);
        
        List<CostType> costTypes = costTypeService.findAll();
        StringBuilder sb = new StringBuilder();
        sb.append("costTypes:[");
        for (CostType costType : costTypes) {
            sb.append(costType.toJSON()).append(",");
        }
        sb.append("]");

        return "accounting/CostList";
    }

    @RequestMapping("/add")
    @ResponseBody
    public void add(@RequestParam("assetTypeId") Integer assetTypeId,
                        @RequestParam("costTypeId") Integer costTypeId,
                        @RequestParam("costDate")Date costDate,
                        @RequestParam("amount") Double amount,
                        @RequestParam("comment") String comment) {
        Cost cost = new Cost();
        cost.setAssetTypeId(assetTypeId);
        cost.setCostTypeId(costTypeId);
        cost.setCostDate(costDate);
        cost.setAmount(amount);
        cost.setComment(comment);
        costService.add(cost);
    }



    public void setCostService(CostService costService) {
        this.costService = costService;
    }


    public void setCostTypeService(CostTypeService costTypeService) {
        this.costTypeService = costTypeService;
    }


}
